package com.conselheiro.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.conselheiro.web.beans.AbstractBean;

public class HomeFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpReq = ((HttpServletRequest) req);
		String contextPath = httpReq.getSession().getServletContext()
				.getContextPath();

//		System.out.println("PathInfo: " + httpReq.getPathInfo());
//		System.out.println("LocalAddr: " + httpReq.getLocalAddr());
//		System.out.println("LocalName" + httpReq.getLocalName());
//		System.out.println("LocalPort: " + httpReq.getLocalPort());
//		System.out.println("RemoteAddr: " + httpReq.getRemoteAddr());
//		System.out.println("RemoteHost: " + httpReq.getRemoteHost());
//		System.out.println("RequestURL: " + httpReq.getRequestURL().toString());
//		System.out.println("RequestURI: " + httpReq.getRequestURI());
//		System.out.println("ServletContext().getServletContextName(): "
//				+ httpReq.getServletContext().getServletContextName());
//		System.out.println("ServletContext().getContextPath(): "
//				+ httpReq.getServletContext().getContextPath());
//
//		System.out.println("Sessao:"
//				+ httpReq.getSession()
//						.getAttribute(AbstractBean.AUTH_KEY_LOGIN));
		if (httpReq.getSession().getAttribute(AbstractBean.AUTH_KEY_LOGIN) == null) {
			chain.doFilter(req, resp);
			return;
		}
		Logger.getLogger(getClass()).info(
				"Acesso indevido. Redirecionando para " + contextPath);
		((HttpServletResponse) resp).sendRedirect(contextPath + "/restrito/");
	}

	public void init(FilterConfig config) throws ServletException {
	}

	public void destroy() {
	}

}
